
export default G6 => {
    G6.registerBehavior('canvas-event', {
        getDefaultCfg() {
            return {
                canvasOffset: [], // 画布偏移距离
                clientOffset: []  // 鼠标移动距离，用于计算画布偏移距离
            }
        },
        getEvents() {
            return {
                'canvas:mousemove': 'onCanvasMouseMove',
                'canvas:mousedown': 'onCanvasMouseDown',
                'canvas:mouseup': 'onCanvasMouseUp',
                'canvas:dragstart': 'onCanvasDragStart',
                'canvas:dragend': 'onCanvasDragEnd',
                'canvas:contextmenu': 'onCanvasContextmenu',
                'canvas:click': 'onCanvasClick'
            }
        },
        onCanvasMouseMove(e) {
            e.target.get('el').style.cursor = 'grab';
        },
        onCanvasMouseDown(e) {
            e.target.get('el').style.cursor = 'grabbing';
        },
        onCanvasMouseUp(e) {
            e.target.get('el').style.cursor = 'grab';
        },
        onCanvasDragStart(e) {
            const { el } = e.target.cfg;
            const dx = +el.getAttribute('dx');
            const dy = +el.getAttribute('dy');

            this.canvasOffset = [dx, dy];
            this.clientOffset = [e.clientX, e.clientY];
        },
        onCanvasDragEnd(e) {
            e.target.get('el').style.cursor = 'grab';
            const { el } = e.target.cfg;
            const dx = this.canvasOffset[0] + e.clientX - this.clientOffset[0];
            const dy = this.canvasOffset[1] + e.clientY - this.clientOffset[1];
            el.setAttribute('dx', dx);
            el.setAttribute('dy', dy);
            this.graph.emit('on-canvas-dragend', {
                ...e,
                dx,
                dy
            });
        },
        onCanvasContextmenu(e) {
            this.graph.emit('on-editor-contextmenu', {
                type: 'canvas',
                event: e
            })
        },
        onCanvasClick() {
            this._clearSelected();
        }, // 清除选中的节点和边样式
        _clearSelected() {
            let graph = this.graph;
            const selectNodes = this.graph.findAllByState('node', 'nodeState:selected');
            selectNodes.forEach(node => {
                graph.setItemState(node, 'nodeState', 'default');
            })
            const selectEdges = this.graph.findAllByState('edge', 'edgeState:selected');
            selectEdges.forEach(edge => {
                graph.setItemState(edge, 'edgeState', 'default');
            })
        }
    })
}